package org.jeecg.modules.kuawcsFs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import org.h2.util.New;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.kuawcsFs.entity.AgKuawcsFs;
import org.jeecg.modules.kuawcsFs.mapper.AgKuawcsFsMapper;
import org.jeecg.modules.kuawcsFs.service.IAgKuawcsFsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description: 跨网传输发送
 * @Author: jeecg-boot
 * @Date:   2020-10-28
 * @Version: V1.0
 */
@Service
public class AgKuawcsFsServiceImpl extends ServiceImpl<AgKuawcsFsMapper, AgKuawcsFs> implements IAgKuawcsFsService {
    @Autowired
    private IAgKuawcsFsService agKuawcsFsService;

    @Value("${kwakcs.erwmjsUrl}")
    String erwmjsUrl ;

    String BOUNDARY = "----WebKitFormBoundarygrBcuHVTeNQcBtqn";
    String name;

    @Override
    public Result<?> sendFile(AgKuawcsFs agKuawcsFs) {
        agKuawcsFs.setFassj(new Date());
        Result result = sendFileByPost(agKuawcsFs);

        if(result.isSuccess()) {
            // 发送成功
            agKuawcsFs.setChuanswcsj(new Date());
            agKuawcsFs.setFasmbbm(agKuawcsFs.getFasmbbm());
//            agKuawcsFs.setFasmbbm("anguan_erweima");
            agKuawcsFs.setFaswjm(agKuawcsFs.getFaswjm());
            agKuawcsFs.setFaswjlj(agKuawcsFs.getFaswjlj());
            agKuawcsFs.setChuansfs(agKuawcsFs.getChuansfs());
            agKuawcsFs.setFassj(agKuawcsFs.getFassj());

            agKuawcsFsService.updateById(agKuawcsFs);
            result.setSuccess(true);
        } else {
            // 发送失败
            agKuawcsFsService.removeById(agKuawcsFs.getId());
            result.error500("发送失败");
        }
        return result;
    }



    // post 方式发送文件
    Result sendFileByPost(AgKuawcsFs agKuawcsFs) {

        Result result = new Result();
        Map<String, Object> params = new HashMap <>();
        Map <String, byte[]> fileParams= new HashMap();
        Map map=new HashMap();
        map.put("sysName", agKuawcsFs.getFasmbbm());
        map.put("fileName", agKuawcsFs.getFaswjm());
        map.put("filePath", agKuawcsFs.getFaswjlj());

        File file = new File(agKuawcsFs.getFaswjlj());


//        if (agKuawcsFs.getChuansfs().startsWith("1")){
 //           params.put(file.getName(),getBytes(file));
//        }
//        else {
            fileParams.put(file.getName(), getBytes(file));
//        }


        try {
//接收文件路径
           byte[] send=  doPost(erwmjsUrl,params,fileParams,map);
    //      byte[] send=  doPost("http://127.0.0.1:9080/jeecg-boot/kuawcsJs/agKuawcsJs/receiveFile",params,fileParams,map);
   //           byte[] send=  doPost("http://127.0.0.1:9080/jeecg-boot/receive",params,fileParams,map);

            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(0);
        }
        return result;
    }
    byte[] doPost(String strUrl, Map <String, Object> params, Map<String, byte[]> fileParams,Map map) throws Exception {
        String urlStr = strUrl
                +"?sysName="+URLEncoder.encode(map.get("sysName").toString(),"utf-8")
                +"&filePath="+URLEncoder.encode(map.get("filePath").toString(),"utf-8")
                +"&fileName="+URLEncoder.encode(map.get("fileName").toString(),"utf-8");//中文乱码

        URL url=new URL(urlStr);
        System.out.println("url"+url);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");

        // 设置接收数据的格式（**重**）
//        connection.setRequestProperty("Accept", "application/json, text/plain, */*"); // 设置接收数据的格式
//        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // 设置发送数据的格式


        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Charset", "UTF-8");

        connection.connect();

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());

        Iterator it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry) it.next();
            String key = entry.getKey();
            Object value = entry.getValue();

            out.writeBytes(value + "\r\n");
        }
        if (fileParams != null && fileParams.size() > 0) {
            Iterator fileIt = fileParams.entrySet().iterator();
            while (fileIt.hasNext()) {
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIt.next();

                out.write(fileEntry.getValue());

            }
        }


        out.flush();

        out.close();

        InputStream in = null;
        int code = connection.getResponseCode();
        try {
            if (code == 200) {
                in = connection.getInputStream();


            } else {
                in = connection.getErrorStream();

            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len;
        while ((len = in.read(buff)) != -1) {
            baout.write(buff, 0, len);
        }
        byte[] bytes = baout.toByteArray();
        in.close();
        return bytes;
    }

    byte[] getBytes(File file) {
        try {
            InputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = in.read(b)) != -1)
                out.write(b, 0, n);
            in.close();
            out.close();

            return out.toByteArray();

        } catch (IOException e) {
            System.out.println("***请设置文件路径***");
        }
        return null;
    }


}
